package com.happyhome.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.happyhome.constants.AppConstant;
import com.happyhome.datamodel.Image;
import com.happyhome.datamodel.Parameter;
import com.happyhome.services.ImageService;
import com.happyhome.services.ParameterService;

@Controller
@RequestMapping("/admin")
public class CommonController {
	
	private static final Logger log = LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	private ParameterService parameterService;
	
	@Autowired
	private ImageService imageService;
	
	@Autowired
	private ServletContext context;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView login() {
		return new ModelAndView("/admin/index");
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout) {
		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", "Invalid username and password!");
		}

		if (logout != null) {
			model.addObject("msg", "You've been logged out successfully.");
		}
		model.setViewName("admin/login");

		return model;
	}
	
	@RequestMapping(value = "/configureParameters", method = RequestMethod.GET)
	public ModelAndView configureParameters() {
		ModelAndView model = new ModelAndView("admin/configureParameters");
		
		List<Parameter> parameters = parameterService.getDataConfigureForCavas();
		model.addObject("listParameters", parameters);
		
		return model;
	}
	
	@RequestMapping(value = "/configureFormParametersSubmit", method = RequestMethod.POST)
	public @ResponseBody String configureFormParametersSubmit(HttpServletRequest request) {
		Map<String, String[]> multiParameters = request.getParameterMap();
		try{
			Parameter first = parameterService.getParameterByCode(multiParameters.get("theFirstOrderValue")[0]);
			first.setValue(Long.parseLong(multiParameters.get("firstOrderOccurrencesValue")[0]));
			first.setOrder(1L);
			parameterService.merge(first);
			
			Parameter second = parameterService.getParameterByCode(multiParameters.get("theSecondOrderValue")[0]);
			second.setValue(Long.parseLong(multiParameters.get("secondOrderOccurrencesValue")[0]));
			second.setOrder(2L);
			parameterService.merge(second);
			
			Parameter third = parameterService.getParameterByCode(multiParameters.get("theThirdOrderValue")[0]);
			third.setValue(Long.parseLong(multiParameters.get("thirdOrderOccurrencesValue")[0]));
			third.setOrder(3L);
			parameterService.merge(third);
			
		}catch(Exception ex){
			ex.printStackTrace();
			log.error(ex.getMessage());
			return "fail";
		}
		
		return "success";
	}
	
	@RequestMapping(value = "/picture/{id}", method = RequestMethod.GET)
    public void picture(HttpServletResponse response, @PathVariable Long id) {
        Image image = imageService.getImageById(id);
        String pathname = context.getRealPath(AppConstant.IMAGE_LOCATION);
        File imageFile = new File(pathname + "/"+ image.getNewFilename());
        response.setContentType(image.getContentType());
        response.setContentLength(image.getSize().intValue());
        try {
            InputStream is = new FileInputStream(imageFile);
            IOUtils.copy(is, response.getOutputStream());
        } catch(IOException e) {
            log.error("Could not show picture "+id, e);
        }
    }
    
    @RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET)
    public void thumbnail(HttpServletResponse response, @PathVariable Long id) {
        Image image = imageService.getImageById(id);
        String pathname = context.getRealPath(AppConstant.IMAGE_LOCATION);
        File imageFile = new File(pathname + "/" + image.getThumbnailFilename());
        response.setContentType(image.getContentType());
        response.setContentLength(image.getThumbnailSize().intValue());
        if(imageFile.exists()){
	        try {
	            InputStream is = new FileInputStream(imageFile);
	            IOUtils.copy(is, response.getOutputStream());
	        } catch(IOException e) {
	            log.error("Could not show thumbnail "+id, e);
	        }
        }
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public @ResponseBody List<Map<String, Object>> delete(@PathVariable Long id) {
        Image image = imageService.getImageById(id);
        String pathname = context.getRealPath(AppConstant.IMAGE_LOCATION);
        File imageFile = new File(pathname + "/" + image.getNewFilename());
        imageFile.delete();
        File thumbnailFile = new File(pathname + "/" + image.getThumbnailFilename());
        thumbnailFile.delete();
        imageService.deleteImageById(image.getId());
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        Map<String, Object> success = new HashMap<String, Object>();
        success.put("success", true);
        results.add(success);
        return results;
    }
}
